package com.xaicode.learn.nio;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * content -> channel -> file
 *
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 1:36
 */
public class NIOFileChannel01 {

    private static final String FILE_PATH = "logs" + File.separator;

    public static void main(String[] args) throws IOException {

        String content = "test nio file channel\nthis is line 2";

        // create file output stream
        FileOutputStream outputStream = new FileOutputStream(FILE_PATH + "NIOFileChannel01.txt");
        // get file channel (FileChannelImpl)
        FileChannel fileChannel = outputStream.getChannel();
        // create buffer
        // ByteBuffer.hb fill with 0
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // put to buffer
        byteBuffer.put(content.getBytes());
        // flip buffer
        byteBuffer.flip();
        // buffer to channel
        fileChannel.write(byteBuffer);

        outputStream.close();
    }

}
